package service

import (
	"fmt"
	"strings"

	"gitee.com/gomaster/book-library/entity"
	"gitee.com/gomaster/book-library/repo"
	"github.com/gin-gonic/gin"
)

// InitBookHandler 初始化图书操作
func InitBookHandler(r *gin.Engine) {
	bookRouter := r.Group("/book")
	bookRouter.POST("/add", AddNewBook)
	bookRouter.POST("/del/:ibsn", DelBook)
	bookRouter.POST("/update/:ibsn", UpdateBook)
	bookRouter.GET("/get/:ibsn", GetBook)
	bookRouter.GET("/list", GetBookList)
}

// AddNewBook 新增加图书
func AddNewBook(c *gin.Context) {
	bookInfo := &entity.BookInfo{}
	err := c.BindJSON(bookInfo)
	if err != nil {
		fmt.Printf("参数错误, err:%s", err.Error())
		c.Errors.JSON()
		return
	}

	handler := repo.GetRepoHandler()
	err = handler.BookAdd(bookInfo)
	if err != nil {
		fmt.Printf("存储图书信息失败")
		c.JSON(200, "store failed")
		return
	}
	entity.ReturnOK(c,nil)
}

// UpdateBook 更新图书信息
func UpdateBook(c *gin.Context) {
	ibsn := c.Param("ibsn")
	if strings.TrimSpace(ibsn) == "" {
		c.JSON(400, "ibsn is null")
	}
	bk := &entity.BookInfo{}
	err := c.BindJSON(bk)
	if err != nil {
		fmt.Printf("获取参数失败, err:%+v", err.Error())
		c.JSON(200, "param is invalid")
		return
	}
	handler := repo.GetRepoHandler()
	err = handler.BookUpdate(ibsn, bk)
	if err != nil {
		fmt.Printf("更新图书失败, err:%+v", err.Error())
		c.JSON(200, "更新图书失败")
	}
	entity.ReturnOK(c,nil)
}

// DelBook 删除图书
func DelBook(c *gin.Context) {
	ibsn := c.Param("ibsn")
	if strings.TrimSpace(ibsn) == "" {
		fmt.Printf("ibsn is null")
		entity.ReturnFail(c, "ibsn cannot be null" )
		return
	}
	handler := repo.GetRepoHandler()
	err := handler.BookDel(ibsn)
	if err != nil {
		fmt.Printf("删除图书失败, ibsn:%s, err:%s", ibsn, err.Error())
		entity.ReturnFail(c, "book delete failed" )
		return
	}
	entity.ReturnOK(c,nil)
}

// GetBook 查询图书
func GetBook(c *gin.Context) {
	ibsn := c.Param("ibsn")
	if strings.TrimSpace(ibsn) == "" {
		fmt.Printf("book ibsn is null")
		entity.ReturnFail(c,"book ibsn is null" )
		return
	}

	bookInfo := repo.GetRepoHandler().BookGet(ibsn)
	entity.ReturnOK(c, bookInfo)
}

// GetBookList 查询图书列表
func GetBookList(c *gin.Context) {
	entity.ReturnOK(c, "todo")
}
